Page({
  data: {
    phone: '',
    smsCode: '',
    password: '',
    password1: '',
    smsCodeButtonText: '获取验证码',
    smsCodeButtonDisabled: false,
    timer: null,
    countdown: 60
  },

  onPhoneInput(event) {
    this.setData({
      phone: event.detail
    });
  },

  onSmsCodeInput(event) {
    this.setData({
      smsCode: event.detail
    });
  },

  onPasswordInput(event) {
    this.setData({
      password: event.detail
    });
  },

  onPasswordInput1(event) {
    this.setData({
      password1: event.detail
    });
  },

  onGetSmsCode() {
    const { phone } = this.data;

    if (!phone) {
      wx.showToast({
        title: '请输入手机号',
        icon: 'none'
      });
      return;
    }

    this.setData({
      smsCodeButtonDisabled: true,
      smsCodeButtonText: `${this.data.countdown}秒`
    });

    this.startCountdown();

    // 在此处调用后台 API 获取验证码
    wx.request({
      url: 'https://your-backend-api.com/getSmsCode', // 替换为你的 API 地址
      method: 'POST',
      data: {
        phone: phone
      },
      success: (res) => {
        wx.showToast({
          title: '验证码已发送',
          icon: 'success'
        });
      },
      fail: (err) => {
        wx.showToast({
          title: '发送失败，请重试',
          icon: 'none'
        });
        this.setData({
          smsCodeButtonDisabled: false,
          smsCodeButtonText: '获取验证码'
        });
        clearInterval(this.data.timer);
      }
    });
  },

  startCountdown() {
    const timer = setInterval(() => {
      let countdown = this.data.countdown - 1;
      if (countdown === 0) {
        clearInterval(this.data.timer);
        this.setData({
          smsCodeButtonDisabled: false,
          smsCodeButtonText: '获取验证码',
          countdown: 60
        });
      } else {
        this.setData({
          countdown: countdown,
          smsCodeButtonText: `${countdown}秒`
        });
      }
    }, 1000);

    this.setData({ timer });
  },

  onRegister() {
    const { phone, smsCode, password, password1 } = this.data;

    if (!phone || !smsCode || !password || !password1) {
      wx.showToast({
        title: '请填写完整信息',
        icon: 'none'
      });
      return;
    }

    if (password !== password1) {
      wx.showToast({
        title: '两次输入的密码不一致',
        icon: 'none'
      });
      return;
    }

    // 在此处执行注册逻辑，例如调用后端 API
    wx.showToast({
      title: '注册成功',
      icon: 'success'
    });
  }
});
